<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" label-width="100" :inline="true"
                style="display: flex;flex-direction: column;align-items: center;">
                <div>
                    <el-form-item label="单位名称">
                        <el-select v-model="searchInfo.unitIds" filterable multiple placeholder="请选择"
                            style="width: 300px;" class="tags-select-input" collapse-tags>
                            <el-option v-for="item in unitData" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="年份">
                        <el-date-picker format="YYYY" value-format="YYYY" v-model="searchInfo.year" type="year"
                            placeholder="请选择" style="width: 300px;" />
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="办公楼名称">
                        <el-input v-model="searchInfo.buildingName" placeholder="请输入" style="width: 300px;" />
                    </el-form-item>
                    <el-form-item label="项目名称">
                        <el-input v-model="searchInfo.name" placeholder="请输入" style="width: 300px;" />
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="年份" prop="year"
                    v-if="checkedColumns.includes('年份')"></el-table-column>
                <el-table-column align="left" label="申请单位" prop="unitName" show-overflow-tooltip
                    v-if="checkedColumns.includes('申请单位')"></el-table-column>
                <el-table-column align="left" label="办公楼名称" prop="buildingName" show-overflow-tooltip
                    v-if="checkedColumns.includes('办公楼名称')"></el-table-column>
                <el-table-column align="left" label="项目名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('项目名称')"></el-table-column>
                <el-table-column align="left" label="申请时间" v-if="checkedColumns.includes('申请时间')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.applyAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="经费匡算" prop="totalFunding"
                    v-if="checkedColumns.includes('经费匡算')"></el-table-column>
                <el-table-column align="left" label="联系人" prop="contacts"
                    v-if="checkedColumns.includes('联系人')"></el-table-column>
                <el-table-column align="left" label="联系电话" prop="contactUs"
                    v-if="checkedColumns.includes('联系电话')"></el-table-column>
                <el-table-column align="left" label="附件" v-if="checkedColumns.includes('附件')">
                    <template #default="scope">
                        <span style="color: #3b82f6;cursor: pointer;" @click="seeFile(scope.row.id)">查看</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="操作" v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == 1" style="color: #3b82f6;cursor: pointer;"
                            @click="seeDetail(scope.row, 'detail')">详情</span>
                        <span v-else style="color: #3b82f6;cursor: pointer;" @click="seeDetail(scope.row)">审批</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false"
            class="sb-draw">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">大中修项目审批</span>
                    <div>
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible && active == 1" :disabled="isDetail" ref="yyglForm" label-width="150"
                :model="form1" :rules="rules">
                <div class="section-title">基本信息</div>
                <el-tabs v-model="form.type" class="demo-tabs" @tab-click="tabChange" style="margin-bottom: 20px;">
                    <el-tab-pane v-for="(item, index) in typeList" :name="index">
                        <template #label>
                            <span class="custom-tabs-label">
                                <span style="margin-right: 4px;">{{ item.system }}</span>
                                <el-icon
                                    v-if="form.detailExamine[index].adoptFunding && form.detailExamine[index].examineNotes">
                                    <CircleCheckFilled color="#4E7DFD" />
                                </el-icon>
                            </span>
                        </template>
                        <el-form-item label="维修项目名称" style="margin-top: 20px;">
                            <el-input v-model="form.name" style="width: 500px;" />
                        </el-form-item>
                        <el-form-item label="办公楼名称">
                            <el-input v-model="form.buildingName" style="width: 500px;" />
                        </el-form-item>
                        <el-form-item label="维修名称">
                            <el-input v-model="typeList[form.type].name" style="width: 500px;" />
                        </el-form-item>
                        <el-form-item label="概要描述">
                            <el-input v-model="typeList[form.type].profile" placeholder="请输入" type="textarea" :rows="3"
                                style="width: 500px;" />
                        </el-form-item>
                        <el-form-item label="匡算">
                            <el-input v-model="typeList[form.type].funding" style="width: 500px;" />
                            <span style="margin-left: 4px;">万元</span>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input v-model="typeList[form.type].notes" type="textarea" :rows="3" placeholder="请输入"
                                style="width: 500px;" />
                        </el-form-item>
                        <div class="section-title">审批意见</div>
                        <el-form-item label="是否纳入计划">
                            <el-radio-group v-model.number="form.detailExamine[index].adopt" class="ml-4">
                                <el-radio :value="1" size="large">纳入计划</el-radio>
                                <el-radio :value="2" size="large">部分纳入计划</el-radio>
                                <el-radio :value="3" size="large">不纳入计划</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="纳入项目计划经费">
                            <el-input v-model="form.detailExamine[index].adoptFunding" style="width: 500px;" @input="(e) => formatValue(e, form.detailExamine[index])"/>
                            <span style="margin-left: 4px;">万元</span>
                        </el-form-item>
                        <el-form-item label="审核说明">
                            <el-input v-model="form.detailExamine[index].examineNotes" type="textarea" :rows="3"
                                placeholder="请输入" style="width: 500px;" />
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
                <el-form-item label="" style="margin-top: 50px;">
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button type="primary" @click="enterDialog">提交审批</el-button>
                    <el-button @click="closeDialog">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <el-drawer v-model="dialog3" :size="1000" :before-close="handleClose3" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">查看附件</span>
                    <div>
                        <el-button @click="closeDialog3">取消</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="fjList" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="文件名" prop="fileName">
                </el-table-column>
                <el-table-column align="left" label="文件类型">
                    <template #default="scope">
                        {{ fileTypes[scope.row.fileType] }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="上传时间">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link icon="download" @click="download(scope.row)">
                            下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    buildingAll,
    unitLists
} from '@/api/unit'
import {
    optionList,
    declareMediumApply,
    declareMedium,
    declareMediumFile,
    declareMediumDetail,
    maintainDeclareMedium,
    declareMediumExamine
} from '@/api/yewuguanli'
import { Calendar } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, computed } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { buildTimeList, countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { Document, Memo,CircleCheckFilled } from '@element-plus/icons-vue'
import { formatTimestamps } from '@/utils/format'
import { fileTypes } from '@/utils/constant';
defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()

const searchInfo = ref({
    name: '',
    type: 1,
    unitIds: [],
    unitName: '',
    buildingName: ''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
    if (fileList1.value.length == 0) {
        callback(new Error('请上传文件'))
    } else {
        callback()
    }
}

const rules = reactive({
    adopt: [{ required: true, message: '请选择办公楼', trigger: 'change' }],
    adoptFunding: [{ required: true, message: '请输入纳入项目计划经费', trigger: 'blur' }],
    examineNotes: [{ required: true, message: '请输入审核说明', trigger: 'blur' }],
})

const active = ref(1)
const form = ref({
    declareId: '',
    detailExamine: [],
    type: 0
})

function tabChange() {

}
const declareDetail = ref([
    // {
    //     system: '承重系统',
    //     name: '',
    //     profile: '',
    //     funding: '',
    //     notes: ''
    // },
    // {
    //     system: '建筑消防系统',
    //     name: '',
    //     profile: '',
    //     funding: '',
    //     notes: ''
    // }
])
const totalNum = computed(() => {
    return declareDetail.value.reduce((prev, next) => prev + Number(next.funding), 0)
})
const form1 = ref({
    buildingId: '',
    name: '',
    change: 1,
    //changeType: '',
    contactUs: '',
    contacts: '',
    estimates: '',
    history: '',
    modelDate: '',
    notes: '',
    totalFunding: '',
    type: 1,
    //year: '',
    checkOptions: [],//自己定义的
    declareDetail: [],
    declareFile: []
})

const initForm = () => {
    //yyglForm.value.resetFields()
    form.value.declareId = ''
    // form.value.detailExamine =[
    //         {
    //             adopt: 1,
    //             adoptFunding: '',
    //             detailId: '',
    //             examineNotes: ''
    //         }
    // ]
    form.value.type = 0
}

const checkedColumns = ref(['序号', '年份', '申请单位', '办公楼名称', '项目名称', '申请时间', '经费匡算', '联系人', '联系电话', '附件', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).dzxsq) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).dzxsq
}
const columns = ref(['序号', '年份', '申请单位', '办公楼名称', '项目名称', '申请时间', '经费匡算', '联系人', '联系电话', '附件', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.dzxsq = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}

const isEdit = ref(false)
const dialogTitle = ref('大中修项目申报')
const addUnit = () => {
    dialogTitle.value = '大中修项目申报'
    isEdit.value = false
    dialogFormVisible.value = true
}

const closeDialog = () => {
    dialogFormVisible.value = false
    initForm()
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
function formatValue(val, item) {
    let temp = val.toString();
    temp = temp.replace(/。/g, ".");
    temp = temp.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    temp = temp.replace(/^\./g, ""); //验证第一个字符是数字
    temp = temp.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
    temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
    item.adoptFunding = temp;
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await maintainDeclareMedium({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}

getTableData()
const buildList = ref([])
const checkOptions = ref([])
const unitData = ref([])
onMounted(() => {
    optionList().then(res => {
        checkOptions.value = res.result
    })
    buildingAll().then(res => {
        buildList.value = res.result
    })
    unitLists().then(res => {
        unitData.value = res.result.data
    })
})

const onSubmit = () => {
    page.value = 1
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        name: '',
        type: 1,
        unitIds: [],
        unitName: '',
        buildingName: ''
    }
    getTableData()
}
const yyglForm = ref(null)
function next() {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            if (active.value == 1) {
                const selectedLabels = checkOptions.value.filter(option => form1.value.checkOptions.includes(option.id)).map(option => option.name)
                declareDetail.value = selectedLabels.map(item => {
                    return {
                        system: item,
                        name: '',
                        profile: '',
                        funding: '',
                        notes: ''
                    }
                })
            }
            if (active.value == 2) {
                let flag = declareDetail.value.some(item => {
                    return !item.name || !item.funding || !item.profile
                })
                if (flag) {//表示没填完整
                    ElMessage({
                        type: 'info',
                        message: '请填写完整信息'
                    })
                    return
                }
                form1.value.declareDetail = declareDetail.value
                form1.value.totalFunding = totalNum.value
            }
            if (active.value == 3) {
                let declareFile = []
                if (fileList1.value.length > 0) {
                    declareFile.push({ fileName: fileList1.value[0].name, fileType: 1, fileUrl: fileList1.value[0].response.result })
                }
                if (fileList2.value.length > 0) {
                    declareFile.push({ fileName: fileList2.value[0].name, fileType: 2, fileUrl: fileList2.value[0].response.result })
                }
                if (fileList3.value.length > 0) {
                    declareFile.push({ fileName: fileList3.value[0].name, fileType: 3, fileUrl: fileList3.value[0].response.result })
                }
                if (fileList4.value.length > 0) {
                    declareFile.push({ fileName: fileList4.value[0].name, fileType: 4, fileUrl: fileList4.value[0].response.result })
                }
                if (fileList5.value.length > 0) {
                    declareFile.push({ fileName: fileList5.value[0].name, fileType: 5, fileUrl: fileList5.value[0].response.result })
                }
                form1.value.declareFile = declareFile
                declareMediumApply(form1.value).then(res => {
                    dialogFormVisible.value = false
                    active.value = 1
                })
            }
            if (active.value < 3) {
                active.value++
            }
            //   let res
            //   if (isEdit.value) {
            //     res = await updateDyn(form.value)
            //   } else {
            //     res = await createDy(form.value)
            //   }
            //   if (res.code == 200) {
            //     ElMessage({
            //       type: 'success',
            //       message: isEdit.value ? '编辑成功' : '添加成功!'
            //     })
            //     getTableData()
            //   }
            //initForm()
            //dialogFormVisible.value = false
        }
    })
}
function downloadTable() {

}
function prev() {
    active.value--
}
const fileList1 = ref([])
const fileList2 = ref([])
const fileList3 = ref([])
const fileList4 = ref([])
const fileList5 = ref([])

function uploadSuccess1(res) {
   
}
function uploadSuccess2(res) {

}
const dialog3 = ref(false)
const fjList = ref([])
function seeFile(id) {
    declareMediumFile(id).then(res => {
        fjList.value = res.result
        dialog3.value = true
    })
}
function handleClose3() {
    dialog3.value = false
}
function closeDialog3() {
    dialog3.value = false
}
const download = (row) => {
    window.open(row.fileUrl)
}
const typeList = ref([])
const isDetail = ref(false)
function seeDetail(row, val) {
    isDetail.value = val == 'detail' ? true : false
    form.value.buildingName = row.buildingName
    form.value.name = row.name
    form.value.declareId = row.id
    form.value.type = 0
    declareMediumDetail(row.id).then(res => {
        typeList.value = res.result
        if (!isDetail.value) {
            if(localStorage.getItem('shenpi')){
                let saveData = JSON.parse(localStorage.getItem('shenpi'))
                let obj = saveData.find(item => item.declareId == row.id)
                if(obj){
                    form.value.detailExamine = obj.detailExamine
                }else{
                    form.value.detailExamine = typeList.value.map(item => {
                    return {
                        adopt: 1,
                        adoptFunding: '',
                        detailId: item.id,
                        examineNotes: ''
                    }
                })
                }
            }else {
                form.value.detailExamine = typeList.value.map(item => {
                    return {
                        adopt: 1,
                        adoptFunding: '',
                        detailId: item.id,
                        examineNotes: ''
                    }
                })
            }
        }
        if (isDetail.value) {
            form.value.detailExamine = typeList.value.map(item => {
                return {
                    adopt: item.adopt || 1,
                    adoptFunding: item.adoptFunding || '',
                    detailId: item.id,
                    examineNotes: item.examineNotes || ''
                }
            })
        }
        dialogFormVisible.value = true
    })
}
function save() {
    let arr = []
    let res = localStorage.getItem('shenpi')
    if (res) {
        arr = JSON.parse(res)
        arr.forEach((item, index) => {
            if (item.declareId == form.value.declareId) {
                arr[index] = form.value
            } else {
                arr.push(form.value)
            }
        })
    } else {
        arr.push(form.value)
    }
    localStorage.setItem('shenpi', JSON.stringify(arr))
    dialogFormVisible.value = false
}
const enterDialog = async () => {
    let flag = form.value.detailExamine.some(item => {
        return !item.adopt || !item.adoptFunding || !item.examineNotes
    })
    if (flag) {
        ElMessage({
            type: 'info',
            message: '请填写完整信息'
        })
        return
    }
    let res = await declareMediumExamine(form.value)
    if (res.code == 200) {
        let result = localStorage.getItem('shenpi')
        if (result) {
            let arr = JSON.parse(result)
            arr = arr.filter(item => item.declareId != form.value.declareId)
            localStorage.setItem('shenpi', JSON.stringify(arr))
        }
        ElMessage({
            type: 'success',
            message: '审批成功'
        })
        initForm()
        dialogFormVisible.value = false
        getTableData()
    }
}
</script>

<style lang="scss">
.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.section-title {
    font-weight: bold;
    font-size: 18px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.sb-draw {
    .title {
        font-size: 16px;
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
    }
}
</style>